﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace BaseMod3
{
    public class TwoLine
    {
        public static Vector3? CalculateLineIntersection( Vector3 P1, Vector3 V1,
    Vector3 Q1, Vector3 V2)
        {
            // 1. 计算共面性
            Vector3 PQ = new Vector3 { X = Q1.X - P1.X, Y = Q1.Y - P1.Y, Z = Q1.Z - P1.Z };
            Vector3 crossV = CrossProduct(V1, V2);
            double mixProduct = DotProduct(PQ, crossV);

            if (Math.Abs(mixProduct) > 1e-6) // 不共面 
                return null;

            // 2. 检查方向向量是否平行 
            if (crossV.X == 0 && crossV.Y == 0 && crossV.Z == 0)
            {
                // 处理共线情况（此处可返回任意点或null）
                return null;
            }

            // 3. 解方程组（以x和y坐标为例）
            double denominator = V1.Y * V2.X - V1.X * V2.Y;
            if (Math.Abs(denominator) < 1e-6) // 分母为零时切换坐标轴计算 
                denominator = V1.Z * V2.X - V1.X * V2.Z;

            double t = (V2.X * (Q1.Y - P1.Y) - V2.Y * (Q1.X - P1.X)) / denominator;

            // 4. 计算交点 
            Vector3 intersection = new Vector3
            {
                X = P1.X + (float)t * V1.X,
                Y = P1.Y + (float)t * V1.Y,
                Z = P1.Z + (float)t * V1.Z
            };

            // 5. 验证Z轴是否满足方程 
            double s_z = (intersection.Z - Q1.Z) / V2.Z;
            if (Math.Abs(Q1.Z + s_z * V2.Z - intersection.Z) > 1e-6)
                return null;

            return intersection;
        }

        // 叉乘与点乘工具方法 
        private static Vector3 CrossProduct(Vector3 a, Vector3 b)
        {
            return new Vector3
            {
                X = a.Y * b.Z - a.Z * b.Y,
                Y = a.Z * b.X - a.X * b.Z,
                Z = a.X * b.Y - a.Y * b.X
            };
        }

        private static double DotProduct(Vector3 a, Vector3 b)
        {
            return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
        }
    }
}
